<?php
/*
 * 首页
 */
namespace app\admin\controller;
use think\facade\Db;
use think\facade\Cache;
use app\common\controller\AdminBase;

use app\common\model\Admin;
use app\common\model\System;

class Index extends AdminBase
{
    protected $noLogin = ['login', 'logout'];//不需要登陆
    protected $noAuth = ['main','index', 'icon','clear'];//不需要权限
    //后台首页
    public function index()
    {
        $uid = md6(AdminId(),true);
        $info = Db::table('admin')->field('user_name,nick_name,mobile_phone,login_count,status')->find($uid);
        $notice = Db::table('notice')->order('create_time','DESC')->find();
        return $this->fetch('index',['notice'=>$notice,'info'=>$info]);
    }
    //默认首页
    public function main()
    {
        //统计信息
        $info = [];
        //用户
        $info['user_add_today'] = Db::table('user')->where(['status'=>1])->whereTime('create_time','today')->count('id');   //当日新增用户
        $info['user_total'] = Db::table('user')->where(['status'=>1])->count('id');   //总用户
        $week_add_user = Db::table('user')->whereWeek('create_time')->count('id')?:1;   //本周会员
        //订单
        $info['order_add_today_sum'] = Db::table('orders')->where(['pay_status'=>1])->whereTime('pay_time','today')->sum('order_amount');   //日销售额
        $info['order_add_today'] = Db::table('orders')->where(['pay_status'=>1])->whereTime('pay_time','today')->count('id');   //日订单
        $info['order_add_week'] = Db::table('orders')->where(['pay_status'=>1])->whereWeek('pay_time')->count('id');   //本周订单
        $info['conversion_rate'] = round($info['order_add_week']/$week_add_user,2);  //周转化率
        //销售额
        $info['order_month_sum'] = Db::table('orders')->where(['pay_status'=>1])->whereMonth('pay_time')->sum('order_amount');   //月销售额
        $info['order_sum'] = Db::table('orders')->where(['pay_status'=>1])->sum('order_amount')/10000;   //总销售额
        $data = Db::table('user')->whereTime('create_time','today')->limit(8)->paginate();
        return $this->fetch('main', ['info'=>$info,'data'=>$data]);
    }
    //获取浏览量
    public function seelog()
    {
        $see = Db::table('see_log')->whereTime('create_time','today')->count();
        $this->success('获取成功','',$see);
    }
    //清除缓存
    public function clear()
    {
        Cache::clear(); 
        $this->success('清除成功');
    }
    //登陆
    public function login()
    {
        $config = System::get_config_by_code('base');
        is_admin_login() && $this->redirect(url('@admin')); // 登录直接跳转
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证规则
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                    $this->validate($param, 'login');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $config['vercode'] == 1 && empty($param['vercode']) && $this->error('请输入验证码');
            $config['vercode'] == 1 && !captcha_check($param['vercode']) && $this->error('验证码错误');
            !empty($param['name']) ? $where = function ($query) use ($param){$query->where('user_name|mobile_phone', trim($param['name']));} : $where = 1; 
            $admin = Db::table('admin')->field('id,user_name,password,salt,status,nick_name')->whereOr($where)->find();
            !$admin && $this->error('账户或密码错误,请查正重试');//账户已删除或不存在
        	$admin['status'] != 1 && $this->error('账户已禁用,请联系管理员');
            $admin['salt'] = $admin['salt']?$admin['salt']:'W5Htd9we';
            $admin['password'] !== morse_code($param['pwd'],$admin['salt']) && $this->error('账户或密码错误,请重试');//密码不正确

            // 保存状态
            $auth = [
                'admin_id' => md6($admin['id']),
                'user_name' => $admin['user_name'],
                'nick_name' => $admin['nick_name'],
            ];
            Session('admin_auth', $auth);
            Session('admin_auth_sign', data_auth_sign($auth));
            // 更新信息
            Db::table('admin')->where('id',$admin['id'])->inc('login_count',1)->update([
                'last_login_time' => time(),
                'last_login_ip'   => $this->request->ip()
            ]);
            // insert_admin_log('登录了后台系统');
            $this->success('登录成功', url('@admin'));
        }

        return $this->fetch('login');
    }

    // 退出登录
    public function logout()
    {
        insert_admin_log('退出了后台系统');
        session('admin_auth', null);
        session('admin_auth_sign', null);
        return $this->redirect(url('admin/index/login'));
    }

    //修改密码
    public function mypass()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            // 验证条件
            $verify = input('_verify', true); 
            if($verify!='0'){
                try{
                    $this->validate($param, 'pass');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $uid = md6(AdminId(),true);
            $admin = Db::table('admin')->find($uid);
            $admin['password'] != morse_code($param['password'],$admin['salt']) && $this->error('旧密码错误');
            $param['plain_code'] = $param['new_password'];//明文密码
            $pwd = morse_code($param['new_password']);
            $data = ['id' => $uid, 'password' => $pwd['password'],'salt' => $pwd['salt'], 'plain_code' => $param['plain_code']];
            $result = Db::table('admin')->update($data);
            !$result && $this->error($this->errorMsg);
            insert_admin_log('修改了登录密码');
            session('admin_auth', null);
            session('admin_auth_sign', null);
            $this->success('修改成功');
        }
        return $this->fetch('myPass');
    }

    //修改个人信息
    public function myinfo()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                    $this->validate($param, 'admin');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $uid = md6(AdminId(),true);
            // 更新信息
            Db::table('admin')->where(['id'=>$uid])->update($param);
            insert_admin_log('修改了个人信息');
            $this->success('修改成功');
        }
        $list = Db::table('admin')->find(md6(AdminId(),true));
        return $this->fetch('myInfo',['list'=>$list]);
    }

}
